let fs = require("fs")
let EventEmitter = require('events')
class WriteStream extends EventEmitter{
    constructor(path, options){
        super(path, options)
        this.path = path
        this.flags = options.flags;
        this.mode = options.mode || 0o666;
        this.start = options.start || 0;
        this.encoding= options.encoding || 'utf8';
        this.autoClose = options.autoClose;
        this.highWaterMark = options.highWaterMark || 16*1024
        this.buffers = []
        this.writing = false; // 内部正在写入数据
        this.length = 0 //缓存区字节的长度
        this.pos = this.start // 文件写入索引
        this.open();
    }

    open(){
        fs.open(this.path, this.flags, this.mode, (err, fd)=>{
            this.fd = fd;
            this.emit('open')
        })
    }
    write(chunk, encoding, cb){
        chunk = Buffer.isBuffer(chunk) ? chunk:Buffer.from(chunk, this.encoding)
        let len = chunk.length
        this.length += len
        let ret = this.length < this.highWaterMark
        if(this.writing){
            this.buffers.push({
                chunk,
                encoding,
                cb
            })
        } else {
            this.writing = true
            this._write(chunk, encoding, ()=>this.clearBuffer())
        }
        return ret
    }

    _write(chunk, encoding, cb){
        if(typeof this.fd != 'number'){
            return this.once('open', ()=>this._write(chunk, encoding, cb))

        }
        fs.write(this.fd, chunk, 0, chunk.length, this.pos, (err, bytesWritten)=>{
            this.pos += bytesWritten
            this.length -= bytesWritten;
            cb && cb()
        })
    }

    clearBuffer(){
        let data = this.buffers.shift();
        if(data){
            this._write(data.chunk, data.encoding, ()=>this.clearBuffer())
        }else{
            this.writing = false
            this.emit('drain')
        }
    }
}